//
//  FileManager.m
//  LoansPresident
//
//  Created by fh on 2018/12/18.
//  Copyright © 2018年 fh. All rights reserved.
//

#import "FileManager.h"

@interface FileManager ()

/**
 创建根目录
 
 @return 根目录完整路径
 */
- (NSString *)createRootDirectoryIfNotExist;

/**
 创建用户文件夹
 
 @return 用户文件夹完整路径
 */
- (NSString *)createAccountDirectoryIfNotExist;

/**
 创建照片文件夹
 
 @return 照片文件夹完整路径
 */
- (NSString *)createPhotoStoreDirectoryIfNotExist;

/**
 创建视频文件夹
 
 @return 视频文件夹完整路径
 */
- (NSString *)createVideoStoreDirectoryIfNotExist;

/**
 同步保存照片到照片文件夹
 
 @param imagePath 要保存的照片源路径
 @param complete 保存结果回调
 */
- (void)synSaveImageWithImagePath:(NSString *)imagePath complete:(void(^)(BOOL saveResult,NSString *imageAbsolutePath))complete;

/**
 同步保存视频到文件夹
 
 @param videoURL 要保存的视频路径
 @param complete 保存结果回调
 */
- (void)synSaveVideoWithVideoURL:(NSURL *)videoURL complete:(void(^)(BOOL saveResult,NSString *videoAbsolutePath))complete;
@end


@implementation FileManager
+ (instancetype)sharedManager {
    static FileManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[FileManager alloc] init];
    });
    return manager;
}

/**
 文件是否存在
 
 @param path 文件路径
 @return 结果
 */
+ (BOOL)fileExistsAtPath:(NSString *)path {
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

/**
 创建文件夹

 @param name 文件夹名字
 @param prePath 要创建的目录路径
 @return 创建文件夹的完整路径
 */
- (NSString *)commonCreateDirectoryWithDirectoryName:(NSString *)name preDirectoryPath:(NSString *)prePath {
    NSString *storePath = [prePath stringByAppendingPathComponent:name];
    if (![[NSFileManager defaultManager] fileExistsAtPath:storePath]) {
        NSError *error = nil;
        // 创建目录
        BOOL result = [[NSFileManager defaultManager] createDirectoryAtPath:storePath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
#ifdef DEBUG
            NSLog(@"创建%@文件夹错误：%@",name,error);
#endif
        }
        if (result) {
            return storePath;
        }else {
            return nil;
        }
    }else {
        return storePath;
    }
}

/**
 创建根目录

 @return 根目录完整路径
 */
- (NSString *)createRootDirectoryIfNotExist {
    NSString *prePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *accountDirectoryName = [NSString stringWithFormat:@"FHPartner"];
    return [self commonCreateDirectoryWithDirectoryName:accountDirectoryName preDirectoryPath:prePath];
}

/**
 创建用户文件夹

 @return 用户文件夹完整路径
 */
- (NSString *)createAccountDirectoryIfNotExist {
    NSString *prePath = [self createRootDirectoryIfNotExist];
//    NSString *accountDirectoryName = [NSString stringWithFormat:@"%@",[AccountManager sharedAccountManager].account];
    NSString *accountDirectoryName = prePath;
    return [self commonCreateDirectoryWithDirectoryName:accountDirectoryName preDirectoryPath:prePath];
}

/**
 创建照片文件夹
 
 @return 照片文件夹完整路径
 */
- (NSString *)createPhotoStoreDirectoryIfNotExist {
    // 暂时不区分账户的文件夹
    NSString *prePath = [self createRootDirectoryIfNotExist];
    NSString *photoDirectoryName = [NSString stringWithFormat:@"Photo"];
    return [self commonCreateDirectoryWithDirectoryName:photoDirectoryName preDirectoryPath:prePath];
}

/**
 创建视频文件夹

 @return 视频文件夹完整路径
 */
- (NSString *)createVideoStoreDirectoryIfNotExist {
    // 暂时不区分账户的文件夹
    NSString *prePath = [self createRootDirectoryIfNotExist];
    NSString *videoDirectoryName = [NSString stringWithFormat:@"Video"];
    return [self commonCreateDirectoryWithDirectoryName:videoDirectoryName preDirectoryPath:prePath];
}

/**
 生成随机名字的文件绝对路径

 @param mimeType 文件类型
 @param prePath 文件上一级目录
 @return 文件绝对路径
 */
- (NSString *)createRandomNameWithMimeType:(NSString *)mimeType prePath:(NSString *)prePath {
    return [prePath stringByAppendingPathComponent:[self createRandomNameWithMimeType:mimeType]];
}

/**
 生成随机名字,如果文件类型为空则不加文件类型后缀
 
 @param mimeType 文件类型
 @return 随机名字
 */
- (NSString *)createRandomNameWithMimeType:(NSString *)mimeType {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *randomName = [NSString stringWithFormat:@"fhPartner_iOS_%@_%u",str,arc4random()%100];
    if (kStringIsNotEmpty(mimeType)) {
        randomName = [randomName stringByAppendingString:[NSString stringWithFormat:@".%@",mimeType]];
    }
    return randomName;
}

/**
 同步保存照片到照片文件夹
 
 @param imagePath 要保存的照片源路径
 @param complete 保存结果回调
 */
- (void)synSaveImageWithImagePath:(NSString *)imagePath complete:(void(^)(BOOL saveResult,NSString *imageAbsolutePath))complete {
    NSString *imgFullName = imagePath.lastPathComponent;
    NSArray<NSString *> *arr = [imgFullName componentsSeparatedByString:@"."];
    NSString *mimeType = arr.lastObject;
    NSString *realSavePath = [self createRandomNameWithMimeType:mimeType prePath:[self createPhotoStoreDirectoryIfNotExist]];
    NSError *copyError = nil;
    BOOL result = [[NSFileManager defaultManager] copyItemAtPath:imagePath toPath:realSavePath error:&copyError];
    if (copyError) {
#ifdef DEBUG
        DBLog(@"保存照片错误信息: %@",copyError);
#endif
    }
    if (complete) {
        complete(result,result?realSavePath:nil);
    }
}

/**
 同步保存视频到文件夹
 
 @param videoURL 要保存的视频路径
 @param complete 保存结果回调
 */
- (void)synSaveVideoWithVideoURL:(NSURL *)videoURL complete:(void(^)(BOOL saveResult,NSString *videoAbsolutePath))complete {
    
    NSString *videoFullName = videoURL.absoluteString.lastPathComponent;
    NSArray<NSString *> *arr = [videoFullName componentsSeparatedByString:@"."];
    NSString *mimeType = arr.lastObject;
    NSString *realSavePath = [self createRandomNameWithMimeType:mimeType prePath:[self createVideoStoreDirectoryIfNotExist]];
    NSError *moveError = nil;
    // 视频采用剪切，防止大视频拷贝过久
    BOOL result = [[NSFileManager defaultManager] moveItemAtURL:videoURL toURL:[NSURL fileURLWithPath:realSavePath] error:&moveError];
    if (moveError) {
#ifdef DEBUG
        DBLog(@"保存视频错误信息: %@",moveError);
#endif
    }
    if (complete) {
        complete(result,result?realSavePath:nil);
    }
}

/**
 保存照片到本地
 
 @param image 要保存的照片
 @param complete 保存结果回调
 */
- (void)syncSaveImage:(UIImage *)image complete:(void (^)(BOOL, NSString *))complete {
    NSString *realSavePath = [self createRandomNameWithMimeType:@"JPG" prePath:[self createPhotoStoreDirectoryIfNotExist]];
    NSData* resultData = UIImageJPEGRepresentation(image, 0.5);
    BOOL result = [resultData writeToFile:realSavePath atomically:YES];
    if (complete) {
        complete(result,result?realSavePath:nil);
    }
}

@end







